<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>C++程序诗篇的灵动赋形：多态 | 澪贰</title><meta name="author" content="澪贰"><meta name="copyright" content="澪贰"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="本篇将开启C++三大特性中的多态篇章，多态允许你以统一的方式处理不同类型的对象，通过相同的接口来调用不同的实现方法。这意味着你可以编写通用的代码，而这些代码可以在运行时根据对象的实际类型来执行特定的操作">
<meta property="og:type" content="article">
<meta property="og:title" content="C++程序诗篇的灵动赋形：多态">
<meta property="og:url" content="http://example.com/2025/04/10/CPP%E8%BF%9B%E9%98%B6/%E5%A4%9A%E6%80%81/index.html">
<meta property="og:site_name" content="澪贰">
<meta property="og:description" content="本篇将开启C++三大特性中的多态篇章，多态允许你以统一的方式处理不同类型的对象，通过相同的接口来调用不同的实现方法。这意味着你可以编写通用的代码，而这些代码可以在运行时根据对象的实际类型来执行特定的操作">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/e36356d92f521a48852de7d58d4e3fa.png">
<meta property="article:published_time" content="2025-04-09T23:00:00.000Z">
<meta property="article:modified_time" content="2025-04-09T23:00:00.000Z">
<meta property="article:author" content="澪贰">
<meta property="article:tag" content="C++">
<meta property="article:tag" content="开发语言">
<meta property="article:tag" content="多态">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/e36356d92f521a48852de7d58d4e3fa.png"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "C++程序诗篇的灵动赋形：多态",
  "url": "http://example.com/2025/04/10/CPP%E8%BF%9B%E9%98%B6/%E5%A4%9A%E6%80%81/",
  "image": "https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/e36356d92f521a48852de7d58d4e3fa.png",
  "datePublished": "2025-04-09T23:00:00.000Z",
  "dateModified": "2025-04-09T23:00:00.000Z",
  "author": [
    {
      "@type": "Person",
      "name": "澪贰",
      "url": "http://example.com/"
    }
  ]
}</script><link rel="shortcut icon" href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/cat_icon.ico"><link rel="canonical" href="http://example.com/2025/04/10/CPP%E8%BF%9B%E9%98%B6/%E5%A4%9A%E6%80%81/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!true && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          const hour = new Date().getHours()
          const isNight = hour <= 6 || hour >= 18
          if (theme === undefined) isNight ? activateDarkMode() : activateLightMode()
          else theme === 'light' ? activateLightMode() : activateDarkMode()
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"未找到符合您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":230,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":150,"languages":{"author":"作者: 澪贰","link":"链接: ","source":"来源: 澪贰","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'medium_zoom',
  Snackbar: {"chs_to_cht":"已切换为繁体中文","cht_to_chs":"已切换为简体中文","day_to_night":"已切换为深色模式","night_to_day":"已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-right"},
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'C++程序诗篇的灵动赋形：多态',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/css/custom.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/echarts@4.9.0/dist/echarts.min.js"></script><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-double-row-display@1.00/cardlistpost.min.css"/>
<style>#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags:before {content:"\A";
  white-space: pre;}#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags > .article-meta__separator{display:none}</style>
<link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-categories-card@1.0.0/lib/categorybar.css"><link rel="stylesheet" href="https://unpkg.zhimg.com/hexo-butterfly-footer-beautify@1.0.0/lib/runtime.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiperstyle.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/animate.min.css" media="print" onload="this.media='screen'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 7.3.0"></head><body><div id="web_bg" style="background-image: url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/water02.jpg);"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/zero_two.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">96</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">74</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">9</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home-lg"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><span class="site-page group hide"><i class="fa-fw fas fa-list"></i><span> 列表</span><i class="fas fa-chevron-down"></i></span><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/e36356d92f521a48852de7d58d4e3fa.png);"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">澪贰</span></a><a class="nav-page-title" href="/"><span class="site-name">C++程序诗篇的灵动赋形：多态</span></a></span><div id="menus"><div id="search-button"><span class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></span></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home-lg"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><span class="site-page group hide"><i class="fa-fw fas fa-list"></i><span> 列表</span><i class="fas fa-chevron-down"></i></span><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-envelope-open"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">C++程序诗篇的灵动赋形：多态</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2025-04-09T23:00:00.000Z" title="发表于 2025-04-10 07:00:00">2025-04-10</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-04-09T23:00:00.000Z" title="更新于 2025-04-10 07:00:00">2025-04-10</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/C-%E8%BF%9B%E9%98%B6/">C++进阶</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">总字数:</span><span class="word-count">5121</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>18分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><div id="post-outdate-notice" data="{&quot;limitDay&quot;:365,&quot;messagePrev&quot;:&quot;It has been&quot;,&quot;messageNext&quot;:&quot;days since the last update, the content of the article may be outdated.&quot;,&quot;postUpdate&quot;:&quot;2025-04-10 07:00:00&quot;}" hidden></div><p>本篇将开启 <code>C++</code> 三大特性中的多态篇章，多态允许你以统一的方式处理不同类型的对象，通过相同的接口来调用不同的实现方法。这意味着你可以编写通用的代码，而这些代码可以在运行时根据对象的实际类型来执行特定的操作</p>
<h1 id="什么是多态？"><a href="#什么是多态？" class="headerlink" title="什么是多态？"></a>什么是多态？</h1><blockquote>
<p>通俗来说，就是多种形态，具体点就是去完成某个行为，当不同的对象去完成时会产生出不同的状态</p>
</blockquote>
<p>✏️<strong>举个例子：</strong></p>
<p>比如买高铁票的时候，我们都属于 <code>Person</code> 类，买的时候会显示为全价，那么我们又属于 <code>Student</code> 类，继承于 <code>Person</code> 类，这时买的时候又会显示为半价，假设两个类都有 <code>BuyTicket</code> 函数，那么相同的函数在继承的基础上，能够实现不同的功能，这就是多态</p>
<h1 id="多态的语法实现"><a href="#多态的语法实现" class="headerlink" title="多态的语法实现"></a>多态的语法实现</h1><h2 id="虚函数"><a href="#虚函数" class="headerlink" title="虚函数"></a>虚函数</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span> </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">BuyTicket</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">	</span>&#123; </span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;买票-全价&quot;</span> &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>被 <code>virtual</code> 修饰的类成员函数称为虚函数，注意这里和菱形虚拟继承的 <code>virtual</code> 没有关系，不过使用了同一个关键字而已</p>
<p>🔥<strong>值得注意的是：</strong> </p>
<ul>
<li>内联函数一般不能是虚函数。内联函数是在编译时将函数体插入到调用处，而虚函数是在运行时进行动态绑定的，两者特性冲突</li>
<li>静态成员不可以是虚函数，虚函数是通过对象的虚函数表指针来实现动态绑定的，也就是在运行时根据对象的实际类型来确定调用哪个虚函数。而静态成员函数是属于类的，不依赖于具体对象，没有对象的概念，也没有虚函数表指针，无法通过动态绑定来调用</li>
<li>构造函数不可以是虚函数，对象中的虚函数表指针是在构造函数初始化列表阶段才初始化的</li>
</ul>
<h2 id="多态的构成"><a href="#多态的构成" class="headerlink" title="多态的构成"></a>多态的构成</h2><p>虚函数是实现多态的重要组成部分，<strong>将上面举的例子以代码形式实现如下：</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span> </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">BuyTicket</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;买票-全价&quot;</span> &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span> : <span class="keyword">public</span> Person </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">BuyTicket</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">	</span>&#123; </span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;买票-半价&quot;</span> &lt;&lt; endl; </span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>多态是在不同继承关系的类对象，去调用同一函数，产生了不同的行为，比如 <code>Student</code> 继承了 <code>Person</code>，<code>Person</code> 对象买票全价，<code>Student</code> 对象买票半价</p>
<p>那么在继承中要构成多态还有两个条件：</p>
<ol>
<li><p>必须通过父类的指针或者引用调用虚函数</p>
</li>
<li><p>被调用的函数必须是虚函数，且派生类必须对基类的虚函数进行重写</p>
</li>
</ol>
<p>🔥<strong>值得注意的是：</strong> 多态构成条件缺一不可，如果多态产生问题，子类没有对某个方法进行重写，那么子类对象在调用该方法时，就会沿着继承链向上查找，找到父类中对应的方法并调用</p>
<h2 id="虚函数的重写"><a href="#虚函数的重写" class="headerlink" title="虚函数的重写"></a>虚函数的重写</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span> </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">BuyTicket</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">	</span>&#123; </span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;买票全价&quot;</span> &lt;&lt; endl; </span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span> : <span class="keyword">public</span> Person </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">BuyTicket</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">	</span>&#123; </span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;买票半价&quot;</span> &lt;&lt; endl; </span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Func</span><span class="params">(Person&amp; people)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	people.<span class="built_in">BuyTicket</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	Person Mike;</span><br><span class="line">	<span class="built_in">Func</span>(Mike);</span><br><span class="line"></span><br><span class="line">	Student Johnson;</span><br><span class="line">	<span class="built_in">Func</span>(Johnson);</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>Person</code> 类的 <code>BuyTicket</code> 和 <code>Student</code> 类的 <code>BuyTicket</code> 构成重写</p>
<p><strong>虚函数的重写：</strong> 又叫覆盖，派生类中有一个跟基类完全相同的虚函数(即派生类虚函数与基类虚函数的<code>返回值类型</code>、<code>函数名字</code>、<code>参数列表</code>完全相同)，<code>称子类的虚函数重写了基类的虚函数</code></p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/dbbee978e4b540ed9ca420eb9814f8f4.png" alt="在这里插入图片描述"></p>
<p>🔥<strong>值得注意的是：</strong> 在重写父类虚函数时，子类的虚函数在不加 <code>virtual</code> 关键字时，虽然也可以构成重写(因为继承后父类的虚函数被继承下来了在子类依旧保持虚函数属性)，但是该种写法不是很规范，不建议这样使用</p>
<h3 id="协变"><a href="#协变" class="headerlink" title="协变"></a>协变</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">A</span> &#123;&#125;;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">B</span> : <span class="keyword">public</span> A &#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span> </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> A* <span class="title">f</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">	</span>&#123; </span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">new</span> A; </span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span> : <span class="keyword">public</span> Person </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> B* <span class="title">f</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">	</span>&#123; </span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">new</span> B; </span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>协变是重写的一种特殊情况，简单来说协变就是<code>派生类重写基类虚函数时，与基类虚函数返回值类型不同</code>，且要求父类虚函数类型和子类虚函数类型必须是<code>父子关系的引用和指针</code></p>
<p>🔥<strong>值得注意的是：</strong> 必须都是引用或者都是指针，不能一个是引用一个是指针</p>
<h3 id="析构函数的重写"><a href="#析构函数的重写" class="headerlink" title="析构函数的重写"></a>析构函数的重写</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span> </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="keyword">virtual</span> ~<span class="built_in">Person</span>() </span><br><span class="line">	&#123; </span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;~Person()&quot;</span> &lt;&lt; endl; </span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span> : <span class="keyword">public</span> Person </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="keyword">virtual</span> ~<span class="built_in">Student</span>() </span><br><span class="line">	&#123; </span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;~Student()&quot;</span> &lt;&lt; endl; </span><br><span class="line">		<span class="keyword">delete</span>[] ptr;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">protected</span>:</span><br><span class="line">	<span class="type">int</span>* ptr = <span class="keyword">new</span> <span class="type">int</span>[<span class="number">10</span>];</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	Person* p = <span class="keyword">new</span> Person;</span><br><span class="line">	<span class="keyword">delete</span> p;</span><br><span class="line">	p = <span class="keyword">new</span> Student;</span><br><span class="line">	<span class="keyword">delete</span> p;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里单纯讲解很难理解，所以以<code>一段代码场景+一些提问</code>来解析：</p>
<p>🚩<strong>析构函数+virtual，是不是虚函数重写？</strong></p>
<p>是，虽然函数名不相同，看起来违背了重写的规则，其实不然，这里可以理解为编译器对析构函数的名称做了特殊处理，编译后析构函数的名称统一处理成 <code>destructor</code></p>
<p>🚩<strong>为什么要处理成统一名字？</strong></p>
<p>因为要让两个析构函数构成重写</p>
<p>🚩<strong>为什么要让他们构成重写？</strong></p>
<p>假设我们上面的这个代码没有加 <code>virtual</code>，运行代码如下：</p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/6b86bc00be61484eb8bdb052af3860a4.png" alt="在这里插入图片描述"></p>
<p>观察可以发现子类 <code>Student</code> 部分没有得到释放，那么 <code>ptr</code> 指向的空间就会造成内存泄漏</p>
<p>根据 <code>C++</code> 内存管理学的知识可知</p>
<blockquote>
<p><code>p</code> -&gt; <code>destructor()</code> + <code>operator delete</code></p>
</blockquote>
<p>这里只能调用 <code>p</code> 这个类型的析构函数，但是我们为了实现能够调用指向空间的析构函数，期望是个多态调用，而不是普通调用，所以必须让这两个析构函数构成重写</p>
<p>🔥<strong>值得注意的是：</strong></p>
<ul>
<li><p>当使用父类指针指向子类对象，析构该指针时，<code>如果父类的析构函数不是虚函数</code>，那么将按指针本身的类型（即父类）来析构。这可能会导致子类部分的资源没有被正确释放，产生内存泄漏等问题</p>
</li>
<li><p><code>如果父类的析构函数是虚函数</code>，那么会按照指针实际指向的对象类型（即子类）来析构</p>
</li>
</ul>
<h2 id="override-和-final"><a href="#override-和-final" class="headerlink" title="override 和 final"></a>override 和 final</h2><p>🚩<strong>final：修饰虚函数，表示该虚函数不能再被重写</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Car</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">Drive</span><span class="params">()</span> <span class="keyword">final</span> </span></span><br><span class="line"><span class="function">	</span>&#123;&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Benz</span> :<span class="keyword">public</span> Car</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">Drive</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">	</span>&#123; </span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;Benz-舒适&quot;</span> &lt;&lt; endl; </span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>🔥<strong>值得注意的是：</strong> </p>
<p>假设有个 <code>A</code> 类和 <code>B</code> 类，不想让 <code>B</code> 类继承 <code>A</code> 类，那么可以写做：<code>class A final</code>，避免 <code>A</code> 类被继承，这是 <code>C++11</code> 才支持的，在这之前使用的是将 <code>A</code> 的构造函数私有化的方法</p>
<p>🚩<strong>override：检查派生类虚函数是否重写了基类某个虚函数，如果没有重写编译报错</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Car</span> </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">Drive</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">	</span>&#123;&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Benz</span> :<span class="keyword">public</span> Car </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">Drive</span><span class="params">()</span> <span class="keyword">override</span> </span></span><br><span class="line"><span class="function">	</span>&#123; </span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;Benz-舒适&quot;</span> &lt;&lt; endl; </span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h1 id="抽象类"><a href="#抽象类" class="headerlink" title="抽象类"></a>抽象类</h1><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Car</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">Drive</span><span class="params">()</span> </span>= <span class="number">0</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Benz</span> :<span class="keyword">public</span> Car</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">Drive</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;Benz-舒适&quot;</span> &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BMW</span> :<span class="keyword">public</span> Car</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">Drive</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;BMW-操控&quot;</span> &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">Test</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	Car* pBenz = <span class="keyword">new</span> Benz;</span><br><span class="line">	pBenz-&gt;<span class="built_in">Drive</span>();<span class="comment">//访问Benz的虚函数</span></span><br><span class="line"></span><br><span class="line">	Car* pBMW = <span class="keyword">new</span> BMW;</span><br><span class="line">	pBMW-&gt;<span class="built_in">Drive</span>();<span class="comment">//访问BMW的虚函数</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在虚函数的后面写上 <code>= 0</code> ，则这个函数为<code>纯虚函数</code>，包含纯虚函数的类叫做<code>抽象类</code>（也叫<code>接口类</code>）</p>
<p>抽象类不能实例化出对象，即只要有纯虚函数就不能实例化出对象，派生类继承后也不能实例化出对象，只有重写纯虚函数，派生类才能实例化出对象。纯虚函数规范了派生类必须重写，另外纯虚函数更体现出了接口继承</p>
<p>🔥<strong>值得注意的是：</strong> </p>
<p>普通函数的继承是一种实现继承，派生类继承了基类函数，可以使用函数，继承的是函数的实现。虚函数的继承是一种接口继承，派生类继承的是基类虚函数的接口，目的是为了重写，达成多态，继承的是接口。所以如果不实现多态，不要把函数定义成虚函数</p>
<h1 id="多态原理"><a href="#多态原理" class="headerlink" title="多态原理"></a>多态原理</h1><h2 id="虚函数表"><a href="#虚函数表" class="headerlink" title="虚函数表"></a>虚函数表</h2><p>✏️<strong>以下我们通过多个例子进行详细解析：</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Base</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">Func1</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;Func1()&quot;</span> &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	<span class="type">int</span> _b = <span class="number">1</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> main</span><br><span class="line">&#123;</span><br><span class="line">	Base b;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>sizeof(Base)是多少？</strong></p>
<blockquote>
<p>想必大部分人第一次做这道题都会觉得是 <code>1</code>，但运行后发现答案是 <code>8</code></p>
</blockquote>
<p>很奇怪，所以我们转到调试查看</p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/f667f0324bb949558803e534298e703c.png" alt="在这里插入图片描述"></p>
<p>发现除了 <code>_b</code> 以外，还多一个 <code>_vfptr</code> 放在对象的前面(注意有些平台可能会放到对象的最后面，这个跟平台有关)，对象中的这个指针我们叫做虚函数表指针( <code>v</code> 代表 <code>virtual</code>，<code>f</code> 代表 <code>function</code>)</p>
<p>通常虚函数都被放在<code>代码段</code>，<code>_vfptr</code> 就是虚函数的地址，被存放在虚函数表，虚函数表放在<code>只读数据段</code>，也就是<code>常量区</code>，所以虚函数表本质上是个<code>函数指针数组</code>，虚函数表是在编译期间生成的</p>
<p>✏️<strong>那么多个虚函数是怎样实现多态的，举个例子：</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Base</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">Func1</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;Base::Func1()&quot;</span> &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">Func2</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;Base::Func2()&quot;</span> &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="type">void</span> <span class="title">Func3</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;Base::Func3()&quot;</span> &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	<span class="type">int</span> _b = <span class="number">1</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Derive</span> : <span class="keyword">public</span> Base</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">Func1</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;Derive::Func1()&quot;</span> &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">	<span class="type">int</span> _d = <span class="number">2</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	Base b;</span><br><span class="line">	Derive d;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>还是转到监视窗口调试查看：</p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/2a39f3b2e76a48a390971567d043656c.png" alt="在这里插入图片描述"></p>
<p><strong>实际上虚函数表是按照一定规则实现的：</strong></p>
<ul>
<li><p>🚩<strong>复制基类虚表内容</strong><br>子类在生成虚表时，首先会把父类虚表中的内容完整地复制一份。这意味着子类虚表初始状态下包含了基类所有虚函数的地址，保证了子类对象可以调用父类的虚函数，这是因为子类继承了基类的接口，在某些情况下可能会使用到基类定义的虚函数实现</p>
</li>
<li><p>🚩<strong>重写虚函数的替换</strong><br>如果子类对父类中的某个虚函数进行了重写，那么在子类虚表中，对应父类虚函数的地址会被替换为子类自己重写后的虚函数地址。当通过父类指针或引用调用该虚函数时，程序会根据对象的实际类型（即子类类型），从子类虚表中找到并重写后的虚函数来执行，从而实现多态性</p>
</li>
<li><p>🚩<strong>新增虚函数的添加</strong><br>对于子类自己新定义的虚函数，会按照它们在子类中声明的先后顺序依次添加到子类虚表的末尾。这些新增的虚函数是子类特有的，父类中并不存在。因此，它们会被单独添加到虚表中，以确保子类对象能够调用这些专属的虚函数</p>
</li>
</ul>
<p>🔥<strong>值得注意的是：</strong> </p>
<ul>
<li>父类 <code>b</code> 对象和子类 <code>d</code> 对象虚表是不一样的，这里我们发现 <code>Func1</code> 完成了重写，所以 <code>d</code> 的虚表中存的是重写的 <code>Derive::Func1</code>，所以虚函数的重写也叫作覆盖，覆盖就是指虚表中虚函数的覆盖。<code>重写</code>是语法的叫法，<code>覆盖</code>是原理层的叫法</li>
<li><code>Func2</code> 继承下来后是虚函数，所以放进了虚表，<code>Func3</code> 也继承下来了，但是不是虚函数，所以不会放进虚表</li>
<li>虚函数表本质是一个存虚函数指针的指针数组，一般情况这个数组最后面放了一个 <code>nullptr</code></li>
<li>一个类的不同对象共享同一个类的虚表</li>
</ul>
<h2 id="多态原理实现"><a href="#多态原理实现" class="headerlink" title="多态原理实现"></a>多态原理实现</h2><p>那么回归到多态的实现条件：</p>
<ol>
<li><p>必须通过父类的指针或者引用调用虚函数</p>
</li>
<li><p>被调用的函数必须是虚函数，且子类必须对父类的虚函数进行重写</p>
</li>
</ol>
<p><strong>我们可以提出两个问题：</strong></p>
<p>🚩<strong>为什么不是子类指针或者引用？</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Animal</span> </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">speak</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;Animal makes a sound&quot;</span> &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Dog</span> : <span class="keyword">public</span> Animal </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="type">void</span> <span class="title">speak</span><span class="params">()</span> <span class="keyword">override</span> </span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;Dog barks&quot;</span> &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Cat</span> : <span class="keyword">public</span> Animal </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="type">void</span> <span class="title">speak</span><span class="params">()</span> <span class="keyword">override</span> </span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;Cat meows&quot;</span> &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    Dog dog;</span><br><span class="line">    Animal* animalPtr = &amp;dog;  <span class="comment">// 父类指针指向子类对象</span></span><br><span class="line">    animalPtr-&gt;<span class="built_in">speak</span>();  <span class="comment">// 运行时根据实际对象类型调用Dog的speak函数</span></span><br><span class="line"></span><br><span class="line">    Cat cat;</span><br><span class="line">    Animal&amp; animalRef = cat;  <span class="comment">// 父类引用绑定到子类对象</span></span><br><span class="line">    animalRef.<span class="built_in">speak</span>();  <span class="comment">// 运行时根据实际对象类型调用Cat的speak函数</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里的子类 <code>Dog</code> 和 <code>Cat</code> 都继承于父类 <code>Animal</code>，就是因为是父类的指针或引用才能想调用哪个子类都行</p>
<p>如果是子类的指针或引用，比如有个 <code>Dog</code> 类的指针 <code>Dog* dogPtr</code>，它只能指向 <code>Dog</code> 类对象，没办法指向 <code>Cat</code> 类对象。如果想用它去调用 <code>speak</code> 函数，不管怎样都是调用 <code>Dog</code> 类的 <code>speak</code> 函数，不能根据实际对象类型（<code>Cat</code> 或其他子类）来动态调用不同的 <code>speak</code> 函数，就实现不了多态了</p>
<p>🚩<strong>为什么不能是父类对象？</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">BuyTicket</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;买票-全价&quot;</span> &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Student</span> : <span class="keyword">public</span> Person</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">BuyTicket</span><span class="params">()</span></span></span><br><span class="line"><span class="function">	</span>&#123;</span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;买票-半价&quot;</span> &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	Person ps;</span><br><span class="line">	Student st;</span><br><span class="line">	ps = st;</span><br><span class="line">	</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果是使用对象，而不是指针或引用，子类中特有的成员变量和函数将被截断，丢失子类的特性</p>
<p>而使用父类指针或引用指向子类对象时，不会发生切片，能够完整保留子类对象的所有信息，从而可以访问子类重写的虚函数以实现多态</p>
<p>🔥<strong>值得注意的是：</strong> 子类对象赋值给父类对象的时候，不会拷贝虚函数表过去，如果拷贝了，那么父类虚函数表中的虚函数就变成子类虚函数了，就失去多态的意义了</p>
<p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/2dd9713af51a46e4b5e1f93aebedaa1d.png" alt="在这里插入图片描述"></p>
<p><strong>所以总结：</strong> 满足多态以后的函数调用，不是在编译时确定的，是运行起来以后到对象的中去找的。不满足多态的函数调用时编译时确认好的</p>
<h2 id="动态绑定与静态绑定"><a href="#动态绑定与静态绑定" class="headerlink" title="动态绑定与静态绑定"></a>动态绑定与静态绑定</h2><p><strong>静态绑定：</strong> 又称为前期绑定(早绑定)，在程序编译期间确定了程序的行为，也称为静态多态，比如：函数重载</p>
<p><strong>动态绑定：</strong> 又称后期绑定(晚绑定)，是在程序运行期间，根据具体拿到的类型确定程序的具体行为，调用具体的函数，也称为动态多态</p>
<h1 id="继承和多态常见的面试问题"><a href="#继承和多态常见的面试问题" class="headerlink" title="继承和多态常见的面试问题"></a>继承和多态常见的面试问题</h1><ol>
<li>下面哪种面向对象的方法可以让你变得富有( )<br><code>A</code>: 继承<br><code>B</code>: 封装<br><code>C</code>: 多态<br><code>D</code>: 抽象</li>
<li>( )是面向对象程序设计语言中的一种机制。这种机制实现了方法的定义与具体的对象无关，<br>而对方法的调用则可以关联于具体的对象。<br><code>A</code>: 继承<br><code>B</code>: 模板<br><code>C</code>: 对象的自身引用<br><code>D</code>: 动态绑定</li>
<li>面向对象设计中的继承和组合，下面说法错误的是？（）<br><code>A</code>：继承允许我们覆盖重写父类的实现细节，父类的实现对于子类是可见的，是一种静态复用，也称为白盒复用<br><code>B</code>：组合的对象不需要关心各自的实现细节，之间的关系是在运行时候才确定的，是一种动态复用，也称为黑盒复用<br><code>C</code>：优先使用继承，而不是组合，是面向对象设计的第二原则<br><code>D</code>：继承可以使子类能自动继承父类的接口，但在设计模式中认为这是一种破坏了父类的封装性的表现</li>
<li>以下关于纯虚函数的说法,正确的是( )<br><code>A</code>：声明纯虚函数的类不能实例化对象<br><code>B</code>：声明纯虚函数的类是虚基类<br><code>C</code>：子类必须实现基类的纯虚函数<br><code>D</code>：纯虚函数必须是空函数</li>
<li>关于虚函数的描述正确的是( )<br><code>A</code>：派生类的虚函数与基类的虚函数具有不同的参数个数和类型<br><code>B</code>：内联函数不能是虚函数<br><code>C</code>：派生类必须重新定义基类的虚函数<br><code>D</code>：虚函数可以是一个static型的函数 </li>
<li>关于虚表说法正确的是（ ）<br><code>A</code>：一个类只能有一张虚表<br><code>B</code>：基类中有虚函数，如果子类中没有重写基类的虚函数，此时子类与基类共用同一张虚表<br><code>C</code>：虚表是在运行期间动态生成的<br><code>D</code>：一个类的不同对象共享该类的虚表</li>
<li>假设A类中有虚函数，B继承自A，B重写A中的虚函数，也没有定义任何虚函数，则（ ）<br><code>A</code>：A类对象的前4个字节存储虚表地址，B类对象前4个字节不是虚表地址<br><code>B</code>：A类对象和B类对象前4个字节存储的都是虚基表的地址<br><code>C</code>：A类对象和B类对象前4个字节存储的虚表地址相同<br><code>D</code>：A类和B类虚表中虚函数个数相同，但A类和B类使用的不是同一张虚表</li>
</ol>
<blockquote>
<p>参考答案：1. <code>A</code>   2. <code>D</code>   3. <code>C</code>   4. <code>A</code>   5. <code>B</code>  6. <code>D</code>  7. <code>D</code></p>
</blockquote>
<ol start="8">
<li>下面程序输出结果是什么? （）</li>
</ol>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">A</span> </span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="built_in">A</span>(<span class="type">const</span> <span class="type">char</span>* s)</span><br><span class="line">	&#123; </span><br><span class="line">		cout &lt;&lt; s &lt;&lt; endl; </span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	~<span class="built_in">A</span>() </span><br><span class="line">	&#123;&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">B</span> :<span class="keyword">virtual</span> <span class="keyword">public</span> A</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="built_in">B</span>(<span class="type">const</span> <span class="type">char</span>* s1, <span class="type">const</span> <span class="type">char</span>* s2)</span><br><span class="line">		:<span class="built_in">A</span>(s1) </span><br><span class="line">	&#123; </span><br><span class="line">		cout &lt;&lt; s2 &lt;&lt; endl; </span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">C</span> :<span class="keyword">virtual</span> <span class="keyword">public</span> A</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="built_in">C</span>(<span class="type">const</span> <span class="type">char</span>* s1, <span class="type">const</span> <span class="type">char</span>* s2)</span><br><span class="line">		:<span class="built_in">A</span>(s1) </span><br><span class="line">	&#123; </span><br><span class="line">		cout &lt;&lt; s2 &lt;&lt; endl; </span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">D</span> :<span class="keyword">public</span> B, <span class="keyword">public</span> C</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="built_in">D</span>(<span class="type">const</span> <span class="type">char</span>* s1, <span class="type">const</span> <span class="type">char</span>* s2, <span class="type">const</span> <span class="type">char</span>* s3, <span class="type">const</span> <span class="type">char</span>* s4)</span><br><span class="line">		:<span class="built_in">B</span>(s1, s2)</span><br><span class="line">		, <span class="built_in">C</span>(s1, s3)</span><br><span class="line">		, <span class="built_in">A</span>(s1)</span><br><span class="line">	&#123;</span><br><span class="line">		cout &lt;&lt; s4 &lt;&lt; endl;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	D* p = <span class="keyword">new</span> <span class="built_in">D</span>(<span class="string">&quot;class A&quot;</span>, <span class="string">&quot;class B&quot;</span>, <span class="string">&quot;class C&quot;</span>, <span class="string">&quot;class D&quot;</span>);</span><br><span class="line">	<span class="keyword">delete</span> p;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p><code>A</code>：class A class B class C class D <code>B</code>：class D class B class C class A<br><code>C</code>：class D class C class B class A <code>D</code>：class A class C class B class D</p>
</blockquote>
<p><strong>解析：</strong> 这是个菱形虚拟继承，所以 <code>A</code> 只会被调用一次，<code>D</code> 类里的初始化列表是按声明的顺序来初始化的，所以按 <code>ABCD</code> 的顺序，因此答案选 <code>A</code> </p>
<ol start="9">
<li>多继承中指针偏移问题？下面说法正确的是( )</li>
</ol>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Base1</span> </span><br><span class="line">&#123; </span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="type">int</span> _b1; </span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Base2</span> </span><br><span class="line">&#123; </span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="type">int</span> _b2; </span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Derive</span> : <span class="keyword">public</span> Base1, <span class="keyword">public</span> Base2 </span><br><span class="line">&#123; </span><br><span class="line"><span class="keyword">public</span>: </span><br><span class="line">	<span class="type">int</span> _d; </span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	Derive d;</span><br><span class="line">	Base1* p1 = &amp;d;</span><br><span class="line">	Base2* p2 = &amp;d;</span><br><span class="line">	Derive* p3 = &amp;d;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p><code>A</code>：p1 &#x3D;&#x3D; p2 &#x3D;&#x3D; p3 <code>B</code>：p1 &lt; p2 &lt; p3 <code>C</code>：p1 &#x3D;&#x3D; p3 !&#x3D; p2 <code>D</code>：p1 !&#x3D; p2 !&#x3D; p3</p>
</blockquote>
<p><strong>解析：</strong> 画图理解即可，选 <code>C</code><br><img src= "" data-lazy-src="https://i-blog.csdnimg.cn/direct/d77f9e16c0594efcb51765b0ed2aba0f.png" alt="在这里插入图片描述"></p>
<ol start="10">
<li>以下程序输出结果是什么（）</li>
</ol>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">A</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">func</span><span class="params">(<span class="type">int</span> val = <span class="number">1</span>)</span> </span></span><br><span class="line"><span class="function">	</span>&#123; </span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;A-&gt;&quot;</span> &lt;&lt; val &lt;&lt; endl; </span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">test</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">	</span>&#123; </span><br><span class="line">		<span class="built_in">func</span>(); </span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">B</span> : <span class="keyword">public</span> A</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">	<span class="function"><span class="type">void</span> <span class="title">func</span><span class="params">(<span class="type">int</span> val = <span class="number">0</span>)</span> </span></span><br><span class="line"><span class="function">	</span>&#123; </span><br><span class="line">		cout &lt;&lt; <span class="string">&quot;B-&gt;&quot;</span> &lt;&lt; val &lt;&lt; endl; </span><br><span class="line">	&#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span>* argv[])</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	B* p = <span class="keyword">new</span> B;</span><br><span class="line">	p-&gt;<span class="built_in">test</span>();</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p><code>A</code>: A-&gt;0 <code>B</code>: B-&gt;1 <code>C</code>: A-&gt;1 <code>D</code>: B-&gt;0 <code>E</code>: 编译出错 <code>F</code>: 以上都不正确</p>
</blockquote>
<p><strong>解析：</strong> 这题绝大多数人肯定会选到 <code>D</code>，这题的知识点确实比较偏，首先我们要知道多态重写的是实现，即只有 <code>&#123;&#125;</code> 内的内容是多态的，实际上子类的函数头其实相当于是从父类拷贝过来的，因此函数头的内容还是调用的父类的，所以答案选 <code>B</code></p>
<hr>
<h1 id="希望读者们多多三连支持"><a href="#希望读者们多多三连支持" class="headerlink" title="希望读者们多多三连支持"></a>希望读者们多多三连支持</h1><h1 id="小编会继续更新"><a href="#小编会继续更新" class="headerlink" title="小编会继续更新"></a>小编会继续更新</h1><h1 id="你们的鼓励就是我前进的动力！"><a href="#你们的鼓励就是我前进的动力！" class="headerlink" title="你们的鼓励就是我前进的动力！"></a>你们的鼓励就是我前进的动力！</h1><p><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/36334dba41264ebfaf00ebf05d8d75c1.gif" alt="请添加图片描述"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="http://example.com">澪贰</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2025/04/10/CPP%E8%BF%9B%E9%98%B6/%E5%A4%9A%E6%80%81/">http://example.com/2025/04/10/CPP进阶/多态/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="http://example.com" target="_blank">澪贰</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/C/">C++</a><a class="post-meta__tags" href="/tags/%E5%BC%80%E5%8F%91%E8%AF%AD%E8%A8%80/">开发语言</a><a class="post-meta__tags" href="/tags/%E5%A4%9A%E6%80%81/">多态</a></div><div class="post-share"><div class="social-share" data-image="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/e36356d92f521a48852de7d58d4e3fa.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i>赞助</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Wechat.png" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Alipay.png" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/Alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><a class="pagination-related" href="/2025/04/19/CPP%E8%BF%9B%E9%98%B6/%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91/" title="C++镌刻数据密码的树之铭文：二叉搜索树"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250407204529.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="info"><div class="info-1"><div class="info-item-1">上一篇</div><div class="info-item-2">C++镌刻数据密码的树之铭文：二叉搜索树</div></div><div class="info-2"><div class="info-item-1">继数据结构的二叉树学习，本篇进行更进一步的搜索二叉树，是一种更为常见的结构 二叉搜索树的概念 二叉搜索树简单来说就是一个排序树  它是具有以下性质的二叉树:  若它的左子树不为空，则左子树上所有节点的值都小于根节点的值 若它的右子树不为空，则右子树上所有节点的值都大于根节点的值 它的左右子树也分别为二叉搜索树  🔥值得注意的是： 每棵子树都满足该性质 二叉搜索树的实现二叉搜索树的结构12345678910111213template&lt;class K&gt;struct BSTreeNode&#123;	BSTreeNode&lt;K&gt;* _left;	BSTreeNode&lt;K&gt;* _right;	K _key;	BSTreeNode(const K&amp; key)		:_left(nullptr)		,_right(nullptr)		,_key(key)	&#123; &#125;&#125;;  _left： 指向左子节点的指针。 _right： 指向右子节点的指针。 _key：...</div></div></div></a><a class="pagination-related" href="/2025/04/07/CPP%E8%BF%9B%E9%98%B6/%E7%BB%A7%E6%89%BF%EF%BC%88%E4%B8%8B%EF%BC%89/" title="C++类间的 “接力棒“ 传递：继承（下）"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/8b5b23ea9bf8a0a0a537fd645a12f3a.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="info text-right"><div class="info-1"><div class="info-item-1">下一篇</div><div class="info-item-2">C++类间的 “接力棒“ 传递：继承（下）</div></div><div class="info-2"><div class="info-item-1">本篇接着补充继承方面的内容，同时本篇的菱形继承尤为重要 继承与友元123456789101112131415161718192021222324252627class Student;class Person&#123;public:	friend void Display(const Person&amp; p, const Student&amp; s);protected:	string _name;&#125;;class Student : public Person&#123;protected:	int _stuNum;&#125;;void Display(const Person&amp; p, const Student&amp; s)&#123;	cout &lt;&lt; p._name &lt;&lt; endl;	cout &lt;&lt; s._stuNum &lt;&lt; endl;&#125;void main()&#123;	Person p;	Student s;	Display(p,...</div></div></div></a></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/2024/11/25/CPP%E5%88%9D%E9%98%B6/C++%E5%85%A5%E9%97%A8%EF%BC%88%E4%B8%8A%EF%BC%89/" title="C++命运石之门代码抉择：C++入门（上）"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241125143913.jpg" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-11-25</div><div class="info-item-2">C++命运石之门代码抉择：C++入门（上）</div></div><div class="info-2"><div class="info-item-1">前言什么是C++  C++ 是一种高级编程语言，它在 C 语言的基础上发展而来的面向对象的语言，C++ 最初是由丹麦计算机科学家本贾尼・斯特劳斯特卢普（Bjarne Stroustrup）在 20 世纪 80 年代初期开发的，当时，C 语言已经在系统编程等领域广泛应用，但对于大型软件项目的开发，缺乏一些如代码复用、数据抽象等方便的机制，简单来说就是对一些自定义类型的完善，C++ 应运而生，它增加了类和对象等面向对象的概念，使得程序可以更好地组织和维护  C++的发展语言的开发都是在原先基础上增加新的语法规则，而不是删掉过去的语法规则，不然会导致以前编程环境下的代码都无法运行（python除外），于是在C语言的基础上进行扩展，增加了类的机制，称之为C with...</div></div></div></a><a class="pagination-related" href="/2024/11/27/CPP%E5%88%9D%E9%98%B6/C++%E5%85%A5%E9%97%A8%EF%BC%88%E4%B8%AD%EF%BC%89/" title="C++命运石之门代码抉择：C++入门（中）"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241127125737.png" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-11-27</div><div class="info-item-2">C++命运石之门代码抉择：C++入门（中）</div></div><div class="info-2"><div class="info-item-1">C语言过渡到C++(中)函数重载是函数的一种特殊情况，C++允许在&#x3D;&#x3D;同一作用域&#x3D;&#x3D;中声明几个功能类似的同名函数，这些同名函数的形参列表不同在于参数个数 或 类型 或 类型顺序常用来处理实现功能类似数据类型不同的问题 函数重载的多种情况🚩参数类型不同 12345678910int Add(int left, int right)&#123;	 cout &lt;&lt; &quot;int Add(int left, int right)&quot; &lt;&lt; endl;	 return left + right;&#125;double Add(double left, double right)&#123;	 cout &lt;&lt; &quot;double Add(double left, double right)&quot; &lt;&lt; endl;	 return left + right;&#125; 一个函数类型为 int ，一个函数类型为 double...</div></div></div></a><a class="pagination-related" href="/2024/11/29/CPP%E5%88%9D%E9%98%B6/C++%E5%85%A5%E9%97%A8%EF%BC%88%E4%B8%8B%EF%BC%89/" title="C++命运石之门代码抉择：C++入门（下）"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241129124329.jpg" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-11-29</div><div class="info-item-2">C++命运石之门代码抉择：C++入门（下）</div></div><div class="info-2"><div class="info-item-1">C语言过渡到C++(下)auto 关键字(C++11)为什么要用 auto？随着后续 C++ 语法的越来越深入，类型的长度可能会越来越长，因为在一些情境下是不允许把全部命名空间全部打开，所以在写类型时可能会遇到以下问题： • 类型难于拼写• 含义不明确导致容易出错 ⌨️比如后续学到迭代器有这么个类型 1std::map&lt;std::string, std::string&gt;::iterator 或许有聪明的人会想到直接用 typedef 给类型取别名不就好了，使用typedef给类型取别名确实可以简化代码，但是 typedef 有会遇到新的难题：  在编程时，常常需要把表达式的值赋值给变量，这就要求在声明变量的时候清楚地知道表达式的类型，然而有时候要做到这点并非那么容易，而且 typedef 只能定死变量的别名，auto 是自动推断的，因此 C++11 给 auto 赋予了新的含义  什么是 auto？早期的 auto：使用auto修饰的变量，是具有自动存储器的局部变量C++11 的新...</div></div></div></a><a class="pagination-related" href="/2025/02/19/CPP%E5%88%9D%E9%98%B6/list%E5%87%BD%E6%95%B0%E5%85%A8%E8%A7%A3/" title="C++效率掌握之STL库：list函数全解"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250218155357.jpg" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-02-19</div><div class="info-item-2">C++效率掌握之STL库：list函数全解</div></div><div class="info-2"><div class="info-item-1">为什么要学习list？什么是list？ list 是 C++ 标准模板库中的一个容器，它实现了双向链表的数据结构。双向链表由一系列节点组成，每个节点包含一个数据元素和两个指针，分别指向前一个节点和后一个节点。在链表的任意位置进行插入和删除操作的时间复杂度都是O(1) 。这使得它在需要频繁插入和删除元素的场景下表现出色，比如实现一个任务调度器，需要不断地添加新任务、移除已完成的任务  list 也是一种很常用的容器，对于链表的处理提供了极大的便利性  list 的主要特征可总结为：  list 是可以在常数范围内在任意位置进行插入和删除的序列式容器，并且该容器可以前后双向迭代 list 的底层是双向链表结构，双向链表中每个元素存储在互不相关的独立节点中，在节点中通过指针指向其前一个元素和后一个元素 list 与 forward_list 非常相似：最主要的不同在于 forward_list 是单链表，只能朝前迭代，已让其更简单高效 与其他的序列式容器相比(array，vector，deque)，list...</div></div></div></a><a class="pagination-related" href="/2025/03/24/CPP%E5%88%9D%E9%98%B6/stack%20&&%20queue%E5%87%BD%E6%95%B0%E5%85%A8%E8%A7%A3/" title="C++效率掌握之STL库：stack &amp;&amp; queue函数全解"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/2a5f5e9a1b71bd497c24494fbc8e93f.png" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-03-24</div><div class="info-item-2">C++效率掌握之STL库：stack &amp;&amp; queue函数全解</div></div><div class="info-2"><div class="info-item-1">本篇是 STL 库专题之 stack 和 queue，本质就是栈和队列，关于该数据结构在初阶数据结构专栏里有详细的解释分析，本篇文章主要针对 stack 和 queue 的使用及拓展进行练习和介绍，建议熟悉好相关的数据结构知识再进行本篇学习  传送门：【初阶数据结构】先来后到的秩序：栈和队列  stack stack 的主要特征可总结为：  stack 是一种容器适配器，专门用在具有后进先出操作的上下文环境中，其删除只能从容器的一端进行元素的插入与提取操作 stack 是作为容器适配器被实现的，容器适配器即是对特定类封装作为其底层的容器，并提供一组特定的成员函数来访问其元素，将特定类作为其底层的，元素特定容器的尾部(即栈顶)被压入和弹出 stack 的底层容器可以是任何标准的容器类模板或者一些其他特定的容器类，这些容器类应该支持以下操作：   empty：判空操作 back：获取尾部元素操作 push_back：尾部插入元素操作 pop_back：尾部删除元素操作   标准容器 vector、deque、list 均符合这些需求，默认情况下，如果没有为 stack...</div></div></div></a><a class="pagination-related" href="/2025/02/04/CPP%E5%88%9D%E9%98%B6/string%E5%87%BD%E6%95%B0%E5%85%A8%E8%A7%A3/" title="C++效率掌握之STL库：string函数全解"><img class="cover" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250203201429.jpg" alt="cover"><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-02-04</div><div class="info-item-2">C++效率掌握之STL库：string函数全解</div></div><div class="info-2"><div class="info-item-1">为什么要学习string？什么是string？ C语言中，字符串是以’\0’结尾的一些字符的集合，为了操作方便，C标准库中提供了一些str系列的库函数，但是这些库函数与字符串是分离开的，不太符合OOP的思想，而且底层空间需要用户自己管理，稍不留神可能还会越界访问  因此创建了string类，比STL库还要早出现，所以有一定的缺陷和冗余  string的主要特征可总结为：  字符串是表示字符序列的类 该类的接口与常规容器的接口基本相同，再添加了一些专门用来操作string的常规操作 string在底层实际是：basic_string模板类的别名typedef basic_string&lt;char, char_traits, allocator&gt;...</div></div></div></a></div></div><hr class="custom-hr"/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="card-info-avatar"><div class="avatar-img"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/zero_two.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-status-box"><div class="author-status"><g-emoji class="g-emoji" alias="palm_tree" fallback-src="https://lskypro.acozycotage.net/LightPicture/2022/12/fe1dc0402e623096.jpg">🤯</g-emoji><span>头脑风暴中</span></div></div></div><div class="author-info-name">澪贰</div><div class="author-info-description"></div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">96</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">74</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">9</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/ZeroCoder-Zhang"><i></i><span>🛫下一站--github</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/ZeroCoder-Zhang" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:1478943685@qq.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content"><center><b>--- 主域名 ---<br><a target="_blank" rel="noopener" href="https://general.zzh-blog.club/" title="主域名链接" class="anno_content"><font color="#5ea6e5">general.zzh-blog.club</font></a></b></center><center><b>--- 推广学习交流(Wechat) ---<br><a target="_blank" rel="noopener" href="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/微信扫码加好友.png" title="微信图片" class="anno_content"><font color="#5ea6e5">zzh1478943685(备注来意)</font></a></b></center></div><div id="welcome-info"></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E5%A4%9A%E6%80%81%EF%BC%9F"><span class="toc-number">1.</span> <span class="toc-text">什么是多态？</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%A4%9A%E6%80%81%E7%9A%84%E8%AF%AD%E6%B3%95%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.</span> <span class="toc-text">多态的语法实现</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%99%9A%E5%87%BD%E6%95%B0"><span class="toc-number">2.1.</span> <span class="toc-text">虚函数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%9A%E6%80%81%E7%9A%84%E6%9E%84%E6%88%90"><span class="toc-number">2.2.</span> <span class="toc-text">多态的构成</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%99%9A%E5%87%BD%E6%95%B0%E7%9A%84%E9%87%8D%E5%86%99"><span class="toc-number">2.3.</span> <span class="toc-text">虚函数的重写</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8D%8F%E5%8F%98"><span class="toc-number">2.3.1.</span> <span class="toc-text">协变</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9E%90%E6%9E%84%E5%87%BD%E6%95%B0%E7%9A%84%E9%87%8D%E5%86%99"><span class="toc-number">2.3.2.</span> <span class="toc-text">析构函数的重写</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#override-%E5%92%8C-final"><span class="toc-number">2.4.</span> <span class="toc-text">override 和 final</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%8A%BD%E8%B1%A1%E7%B1%BB"><span class="toc-number">3.</span> <span class="toc-text">抽象类</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%A4%9A%E6%80%81%E5%8E%9F%E7%90%86"><span class="toc-number">4.</span> <span class="toc-text">多态原理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%99%9A%E5%87%BD%E6%95%B0%E8%A1%A8"><span class="toc-number">4.1.</span> <span class="toc-text">虚函数表</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%9A%E6%80%81%E5%8E%9F%E7%90%86%E5%AE%9E%E7%8E%B0"><span class="toc-number">4.2.</span> <span class="toc-text">多态原理实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8A%A8%E6%80%81%E7%BB%91%E5%AE%9A%E4%B8%8E%E9%9D%99%E6%80%81%E7%BB%91%E5%AE%9A"><span class="toc-number">4.3.</span> <span class="toc-text">动态绑定与静态绑定</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BB%A7%E6%89%BF%E5%92%8C%E5%A4%9A%E6%80%81%E5%B8%B8%E8%A7%81%E7%9A%84%E9%9D%A2%E8%AF%95%E9%97%AE%E9%A2%98"><span class="toc-number">5.</span> <span class="toc-text">继承和多态常见的面试问题</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%B8%8C%E6%9C%9B%E8%AF%BB%E8%80%85%E4%BB%AC%E5%A4%9A%E5%A4%9A%E4%B8%89%E8%BF%9E%E6%94%AF%E6%8C%81"><span class="toc-number">6.</span> <span class="toc-text">希望读者们多多三连支持</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%B0%8F%E7%BC%96%E4%BC%9A%E7%BB%A7%E7%BB%AD%E6%9B%B4%E6%96%B0"><span class="toc-number">7.</span> <span class="toc-text">小编会继续更新</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BD%A0%E4%BB%AC%E7%9A%84%E9%BC%93%E5%8A%B1%E5%B0%B1%E6%98%AF%E6%88%91%E5%89%8D%E8%BF%9B%E7%9A%84%E5%8A%A8%E5%8A%9B%EF%BC%81"><span class="toc-number">8.</span> <span class="toc-text">你们的鼓励就是我前进的动力！</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2025/07/28/Linux/Linux%E7%8E%AF%E5%A2%83%E5%9F%BA%E7%A1%80%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7%E4%BD%BF%E7%94%A8/" title="【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250728114434.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用"/></a><div class="content"><a class="title" href="/2025/07/28/Linux/Linux%E7%8E%AF%E5%A2%83%E5%9F%BA%E7%A1%80%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7%E4%BD%BF%E7%94%A8/" title="【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用">【Linux操作系统】简学深悟启示录：Linux环境基础开发工具使用</a><time datetime="2025-07-28T13:41:39.000Z" title="发表于 2025-07-28 21:41:39">2025-07-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/07/14/Linux/Linux%E6%9D%83%E9%99%90/" title="【Linux操作系统】简学深悟启示录：Linux权限"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250713233449.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【Linux操作系统】简学深悟启示录：Linux权限"/></a><div class="content"><a class="title" href="/2025/07/14/Linux/Linux%E6%9D%83%E9%99%90/" title="【Linux操作系统】简学深悟启示录：Linux权限">【Linux操作系统】简学深悟启示录：Linux权限</a><time datetime="2025-07-13T22:00:00.000Z" title="发表于 2025-07-14 06:00:00">2025-07-14</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/07/07/Linux/Linux%E5%9F%BA%E6%9C%AC%E6%8C%87%E4%BB%A4/" title="【Linux操作系统】简学深悟启示录：Linux基本指令"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250705182234.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【Linux操作系统】简学深悟启示录：Linux基本指令"/></a><div class="content"><a class="title" href="/2025/07/07/Linux/Linux%E5%9F%BA%E6%9C%AC%E6%8C%87%E4%BB%A4/" title="【Linux操作系统】简学深悟启示录：Linux基本指令">【Linux操作系统】简学深悟启示录：Linux基本指令</a><time datetime="2025-07-07T12:31:51.000Z" title="发表于 2025-07-07 20:31:51">2025-07-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%8B%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（下）"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250608235413.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【前端基础】层叠宇宙的代码旅人：css（下）"/></a><div class="content"><a class="title" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%8B%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（下）">【前端基础】层叠宇宙的代码旅人：css（下）</a><time datetime="2025-06-23T07:47:50.000Z" title="发表于 2025-06-23 15:47:50">2025-06-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%AD%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（中）"><img src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/909e58aa338befce9e0b2e4e683d50c.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【前端基础】层叠宇宙的代码旅人：css（中）"/></a><div class="content"><a class="title" href="/2025/06/23/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/css%EF%BC%88%E4%B8%AD%EF%BC%89/" title="【前端基础】层叠宇宙的代码旅人：css（中）">【前端基础】层叠宇宙的代码旅人：css（中）</a><time datetime="2025-06-23T07:44:20.000Z" title="发表于 2025-06-23 15:44:20">2025-06-23</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2024 - 2025 By 澪贰</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo 7.3.0</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly 5.3.5</a></div><div class="footer_custom_text">🏃‍➡️不是遇到同行伙伴再出发，而是出发后的路上遇到志同道合的人。<p></a>&nbsp;<a target="_blank" href="https://www.jsdelivr.com/"><img src= "" data-lazy-src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a> &nbsp;<a target="_blank" href="https://vercel.com/ "><img src= "" data-lazy-src="https://img.shields.io/badge/Hosted-Vervel-brightgreen?style=flat&logo=Vercel" title="本站采用双线部署，默认线路托管于Vercel"></a>&nbsp;<a target="_blank" href="https://vercel.com/ "><img src= "" data-lazy-src="https://img.shields.io/badge/Hosted-Coding-0cedbe?style=flat&logo=Codio" title="本站采用双线部署，联通线路托管于Coding"></a>&nbsp;<a target="_blank" href="https://github.com/"><img src= "" data-lazy-src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&logo=GitHub" title="本站项目由Gtihub托管"></a>&nbsp;<a target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img src= "" data-lazy-src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></p></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="前往评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"><span id="percent">0</span><span>%</span></i></button><button id="go-down" type="button" title="直达底部" onclick="btf.scrollToDest(document.body.scrollHeight, 500)"><i class="fas fa-arrow-down"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>(() => {
  const isShuoshuo = GLOBAL_CONFIG_SITE.pageType === 'shuoshuo'
  const option = null

  const getCount = () => {
    const countELement = document.getElementById('twikoo-count')
    if(!countELement) return
    twikoo.getCommentsCount({
      envId: 'https://twikoo.zzh-blog.club/',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(res => {
      countELement.textContent = res[0].count
    }).catch(err => {
      console.error(err)
    })
  }

  const init = (el = document, path = location.pathname) => {
    twikoo.init({
      el: el.querySelector('#twikoo-wrap'),
      envId: 'https://twikoo.zzh-blog.club/',
      region: '',
        placeholder: "|´・ω・)ノ嘿~都看到这儿了\n确定不评论一下再走嘛？\n(点完发送按钮等几秒哦~)",
        nicknamePlaceholder: "昵称/笔名",
        emailPlaceholder: "邮箱（不会公开）",
        urlPlaceholder: "个人站点",
      onCommentLoaded: () => {
        btf.loadLightbox(document.querySelectorAll('#twikoo .tk-content img:not(.tk-owo-emotion)'))
      },
      ...option,
      path: isShuoshuo ? path : (option && option.path) || path
    })

    

    isShuoshuo && (window.shuoshuoComment.destroyTwikoo = () => {
      if (el.children.length) {
        el.innerHTML = ''
        el.classList.add('no-comment')
      }
    })
  }

  const loadTwikoo = (el, path) => {
    if (typeof twikoo === 'object') setTimeout(() => init(el, path), 0)
    else btf.getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(() => init(el, path))
  }

  if (isShuoshuo) {
    'Twikoo' === 'Twikoo'
      ? window.shuoshuoComment = { loadComment: loadTwikoo }
      : window.loadOtherComment = loadTwikoo
    return
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo()
  } else {
    window.loadOtherComment = loadTwikoo
  }
})()</script></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script defer data-pjax src="/js/cat.js"></script><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script async src="/js/title.js"></script><script async src="//npm.elemecdn.com/pace-js@1.2.4/pace.min.js"></script><script defer data-pjax src="/js/readPercent.js"></script><div class="aplayer no-destroy" data-id="8459282733" data-server="netease" data-type="playlist" data-fixed="true" data-autoplay="true" data-listmaxheight=400px data-order="random"> </div><script src="https://cdn.staticfile.org/jquery/3.6.3/jquery.min.js"></script><script async data-pjax src="/js/txmap.js"></script><script src="source/js/统计图颜色适配.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="true"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script>(() => {
  const destroyAplayer = () => {
    if (window.aplayers) {
      for (let i = 0; i < window.aplayers.length; i++) {
        if (!window.aplayers[i].options.fixed) {
          window.aplayers[i].destroy()
        }
      }
    }
  }

  const runMetingJS = () => {
    typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()
  }

  btf.addGlobalFn('pjaxSend', destroyAplayer, 'destroyAplayer')
  btf.addGlobalFn('pjaxComplete', loadMeting, 'runMetingJS')
})()</script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>(() => {
  const pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

  window.pjax = new Pjax({
    elements: 'a:not([target="_blank"])',
    selectors: pjaxSelectors,
    cacheBust: false,
    analytics: false,
    scrollRestoration: false
  })

  const triggerPjaxFn = (val) => {
    if (!val) return
    Object.values(val).forEach(fn => fn())
  }

  document.addEventListener('pjax:send', () => {
    // removeEventListener
    btf.removeGlobalFnEvent('pjaxSendOnce')
    btf.removeGlobalFnEvent('themeChange')

    // reset readmode
    const $bodyClassList = document.body.classList
    if ($bodyClassList.contains('read-mode')) $bodyClassList.remove('read-mode')

    triggerPjaxFn(window.globalFn.pjaxSend)
  })

  document.addEventListener('pjax:complete', () => {
    btf.removeGlobalFnEvent('pjaxCompleteOnce')
    document.querySelectorAll('script[data-pjax]').forEach(item => {
      const newScript = document.createElement('script')
      const content = item.text || item.textContent || item.innerHTML || ""
      Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
      newScript.appendChild(document.createTextNode(content))
      item.parentNode.replaceChild(newScript, item)
    })

    triggerPjaxFn(window.globalFn.pjaxComplete)
  })

  document.addEventListener('pjax:error', e => {
    if (e.request.status === 404) {
      const usePjax = true
      true 
        ? (usePjax ? pjax.loadUrl('/404.html') : window.location.href = '/404.html')
        : window.location.href = e.request.responseURL
    }
  })
})()</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="text-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="输入你想搜索的关键字" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div><!-- hexo injector body_end start --><script data-pjax>
    function butterfly_categories_card_injector_config(){
      var parent_div_git = document.getElementById('recent-posts');
      var item_html = '<style>li.categoryBar-list-item{width:24%;}.categoryBar-list{max-height: 380px;overflow:auto;}.categoryBar-list::-webkit-scrollbar{width:0!important}@media screen and (max-width: 650px){.categoryBar-list{max-height: 320px;}}</style><div class="recent-post-item" style="height:auto;width:100%;padding:0px;"><div id="categoryBar"><ul class="categoryBar-list"><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163139.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Linux/&quot;);" href="javascript:void(0);">Linux</a><span class="categoryBar-list-count">3</span><span class="categoryBar-list-descr">C++笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163140.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/C-初阶/&quot;);" href="javascript:void(0);">C++初阶</a><span class="categoryBar-list-count">19</span><span class="categoryBar-list-descr">C语言笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_202507101631401.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/C语言/&quot;);" href="javascript:void(0);">C语言</a><span class="categoryBar-list-count">22</span><span class="categoryBar-list-descr">Linux笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163130.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/Microi吾码/&quot;);" href="javascript:void(0);">Microi吾码</a><span class="categoryBar-list-count">2</span><span class="categoryBar-list-descr">C++笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163135.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/C-进阶/&quot;);" href="javascript:void(0);">C++进阶</a><span class="categoryBar-list-count">19</span><span class="categoryBar-list-descr">低代码</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163137.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/优选算法/&quot;);" href="javascript:void(0);">优选算法</a><span class="categoryBar-list-count">11</span><span class="categoryBar-list-descr">数据结构笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163136.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/前端基础/&quot;);" href="javascript:void(0);">前端基础</a><span class="categoryBar-list-count">5</span><span class="categoryBar-list-descr">入门常用算法</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163132.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/话题/&quot;);" href="javascript:void(0);">话题</a><span class="categoryBar-list-count">5</span><span class="categoryBar-list-descr">前端基础笔记</span></li><li class="categoryBar-list-item" style="background:url(https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250710163134.png);"> <a class="categoryBar-list-link" onclick="pjax.loadUrl(&quot;categories/初阶数据结构/&quot;);" href="javascript:void(0);">初阶数据结构</a><span class="categoryBar-list-count">10</span><span class="categoryBar-list-descr">杂谈</span></li></ul></div></div>';
      console.log('已挂载butterfly_categories_card')
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      }
    if( document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    butterfly_categories_card_injector_config()
    }
  </script><script data-pjax>
  function butterfly_footer_beautify_injector_config(){
    var parent_div_git = document.getElementById('footer-wrap');
    var item_html = '<div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" style="margin-inline:5px" data-title="博客框架为Hexo" title=""><img src= "" data-lazy-src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&amp;logo=hexo" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" style="margin-inline:5px" data-title="主题使用Butterfly" title=""><img src= "" data-lazy-src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&amp;logo=bitdefender" alt=""/></a></p>';
    console.log('已挂载butterfly_footer_beautify')
    parent_div_git.insertAdjacentHTML("beforeend",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_footer_beautify_injector_config();
  }
  else if (epage === cpage){
    butterfly_footer_beautify_injector_config();
  }
  </script><script async src="https://unpkg.zhimg.com/hexo-butterfly-footer-beautify@1.0.0/lib/runtime.min.js"></script><script data-pjax>
  function butterfly_swiper_injector_config(){
    var parent_div_git = document.getElementById('recent-posts');
    var item_html = '<div class="recent-post-item" style="height: auto;width: 100%"><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container"><div class="blog-slider__wrp swiper-wrapper" style="transition-duration: 0ms;"><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/28/话题/DeepSeek、Grok 和 ChatGPT 对比分析/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/77c5921463a44f418828ae47de6671e5.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-28</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/28/话题/DeepSeek、Grok 和 ChatGPT 对比分析/&quot;);" href="javascript:void(0);" alt="">DeepSeek、Grok 和 ChatGPT 对比分析：从技术与应用场景的角度深入探讨</a><div class="blog-slider__text">在人工智能领域，随着技术的快速发展，不同的工具和框架不断涌现，为开发者提供了更多选择。DeepSeek、Grok 和 ChatGPT 作为三款备受关注的工具，每一款都有其独特的优势和适用场景。本文将从技术特点、应用场景以及实际案例分析的角度，对这三款工具进行对比，帮助读者更好地理解它们的区别和适用场景</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/28/话题/DeepSeek、Grok 和 ChatGPT 对比分析/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/20/话题/C++方向后端开发学习指南/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/44fa280c73e53024f749363207753e1.png" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-20</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/20/话题/C++方向后端开发学习指南/&quot;);" href="javascript:void(0);" alt="">当前就业形势下C++方向后端开发学习指南</a><div class="blog-slider__text">在信息技术飞速发展的今天，后端开发成为了软件开发领域中极其重要的组成部分。对于很多程序员来说，C++仍然是一个强大且广泛应用的编程语言，尤其在后端开发中有着不可忽视的地位。本文将深入探讨C++方向后端开发的学习路线，分析当前就业形势下的职业方向选择，并结合图示和代码示例，帮助读者系统化地学习C++后端开发</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/20/话题/C++方向后端开发学习指南/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/20/话题/AIGC训练效率/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/419f4f95b11526f92f62fe38778d0a9.png" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-20</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/20/话题/AIGC训练效率/&quot;);" href="javascript:void(0);" alt="">AIGC训练效率与模型优化的深入探讨</a><div class="blog-slider__text">人工智能领域的发展，人工智能生成内容（ [AIGC](https://aigc.izzi.cn/)）越来越受关注。AIGC能够通过学习大量数据生成高质量内容，但训练效率和模型优化仍然是关键的研究方向。本博客将深入探AIGC的训练效率，与模型优化的相关策略和技术，提供相应代码示例和图示，以帮助读者更好地理解该领域</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/20/话题/AIGC训练效率/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/02/28/话题/如何高效利用DeepSeek/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/e640e59c2f92482993b52c845adf7844.webp" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-02-28</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/02/28/话题/如何高效利用DeepSeek/&quot;);" href="javascript:void(0);" alt="">如何高效利用DeepSeek：深入探索AI搜索引擎的潜力</a><div class="blog-slider__text">随着人工智能技术的飞速发展，传统的搜索引擎正逐步向更智能化、个性化的方向演进。作为一款基于深度学习的AI搜索引擎，DeepSeek（深度求索）不仅在理解用户意图方面展现出色，还通过集成丰富的知识图谱和提供多样化的信息类型，成为现代用户的信息获取利器。本文将详细分析如何高效利用DeepSeek，探讨其核心技术、实际应用场景以及性能优化方法</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/02/28/话题/如何高效利用DeepSeek/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" onclick="pjax.loadUrl(&quot;2025/01/31/话题/本地部署Deepseek/&quot;);" href="javascript:void(0);" alt=""><img width="48" height="48" src= "" data-lazy-src="https://picture-bed000.oss-cn-shenzhen.aliyuncs.com/2373381f0feae7cd4964af546e9e462.png" alt="" onerror="this.src=https://unpkg.zhimg.com/akilar-candyassets/image/loading.gif; this.onerror = null;"/></a><div class="blog-slider__content"><span class="blog-slider__code">2025-01-31</span><a class="blog-slider__title" onclick="pjax.loadUrl(&quot;2025/01/31/话题/本地部署Deepseek/&quot;);" href="javascript:void(0);" alt="">如何快速高效本地部署DeepseekR1大模型？保姆级教程 无惧隐私威胁</a><div class="blog-slider__text">DeepSeek 隐私政策中提到了关于用户输入信息收集的条款，无论你输入什么文本，以及上传什么文件都会被第三方机构所收集，所以如果是在进行相关的项目研究或者实验进展分析的时候，就很有必要对数据进行隐私保护，且本地部署是支持离线的</div><a class="blog-slider__button" onclick="pjax.loadUrl(&quot;2025/01/31/话题/本地部署Deepseek/&quot;);" href="javascript:void(0);" alt="">详情       </a></div></div></div><div class="blog-slider__pagination swiper-pagination-clickable swiper-pagination-bullets"></div></div></div>';
    console.log('已挂载butterfly_swiper')
    parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  var elist = 'undefined'.split(',');
  var cpage = location.pathname;
  var epage = '/';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_swiper_injector_config();
  }
  else if (epage === cpage){
    butterfly_swiper_injector_config();
  }
  </script><script defer src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper.min.js"></script><script defer data-pjax src="https://npm.elemecdn.com/hexo-butterfly-swiper/lib/swiper_init.js"></script><script data-pjax src="https://npm.elemecdn.com/hexo-filter-gitcalendar/lib/gitcalendar.js"></script><script data-pjax>
  function gitcalendar_injector_config(){
      var parent_div_git = document.getElementById('gitZone');
      var item_html = '<div class="recent-post-item" id="gitcalendarBar" style="width:100%;height:auto;padding:10px;"><style>#git_container{min-height: 280px}@media screen and (max-width:650px) {#git_container{min-height: 0px}}</style><div id="git_loading" style="width:10%;height:100%;margin:0 auto;display: block;"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50" xml:space="preserve"><path fill="#d0d0d0" d="M25.251,6.461c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615V6.461z" transform="rotate(275.098 25 25)"><animatetransform attributeType="xml" attributeName="transform" type="rotate" from="0 25 25" to="360 25 25" dur="0.6s" repeatCount="indefinite"></animatetransform></path></svg><style>#git_container{display: none;}</style></div><div id="git_container"></div></div>';
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
      console.log('已挂载gitcalendar')
      }

    if( document.getElementById('gitZone') && (location.pathname ==='/about/'|| '/about/' ==='all')){
        gitcalendar_injector_config()
        GitCalendarInit("https://gitcalendar.zzh-blog.club/api?ZeroCoder-Zhang",['#d9e0df', '#c6e0dc', '#a8dcd4', '#9adcd2', '#89ded1', '#77e0d0', '#5fdecb', '#47dcc6', '#39dcc3', '#1fdabe', '#00dab9'],'ZeroCoder-Zhang')
    }
  </script><div class="js-pjax"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '2s');
    arr[i].setAttribute('data-wow-delay', '1s');
    arr[i].setAttribute('data-wow-offset', '100');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__zoomIn');
    arr[i].setAttribute('data-wow-duration', '');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script></div><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow.min.js"></script><script defer src="https://npm.elemecdn.com/hexo-butterfly-wowjs/lib/wow_init.js"></script><!-- hexo injector body_end end --><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/koharu.model.json"},"display":{"position":"right","hOffset":40,"vOffset":0,"width":150,"height":300},"mobile":{"show":false},"log":false});</script></body></html>